const BASE_URL = 'https://service.rcar.vip';

// Token management
export function getToken() {
  return localStorage.getItem('userToken');
}

export function setToken(token) {
  if (token) {
    localStorage.setItem('userToken', token);
  }
}

export function removeToken() {
  localStorage.removeItem('userToken');
}

export function request(config) {
  return new Promise((resolve, reject) => {
    if (!config || !config.url) {
      reject(new Error('request config.url is required'));
      return;
    }
    
    const method = config.method ? config.method.toUpperCase() : 'GET';
    const token = getToken();
    const headers = Object.assign({}, config.header || {});
    
    if (token && !headers.token) {
      headers.token = token;
    }
    
    if (method !== 'GET' && !headers['content-type']) {
      headers['content-type'] = 'application/json';
    }
    
    const data = typeof config.data !== 'undefined'
      ? config.data
      : typeof config.params !== 'undefined'
      ? config.params
      : {};
    
    const rawUrl = config.url;
    let fullUrl = rawUrl.indexOf('http') === 0 ? rawUrl : BASE_URL + rawUrl;

    try {
      const urlObj = new URL(fullUrl);
      urlObj.searchParams.set('yj-test', 'true');
      fullUrl = urlObj.toString();
    } catch (e) {
      const separator = fullUrl.includes('?') ? '&' : '?';
      fullUrl = `${fullUrl}${separator}yj-test=true`;
    }
    
    fetch(fullUrl, {
      method,
      headers,
      body: method !== 'GET' ? JSON.stringify(data) : undefined,
      signal: config.signal
    })
    .then(async (res) => {
      // Extract token from response headers
      const responseToken = res.headers.get('token');
      if (responseToken) {
        setToken(responseToken);
      }
      
      const responseData = await res.json();
      const response = {
        statusCode: res.status,
        data: responseData,
        header: Object.fromEntries(res.headers.entries())
      };
      
      resolve(response);
    })
    .catch((error) => {
      reject(error);
    });
  });
}

export function get(url, params, header) {
  const queryString = params ? '?' + new URLSearchParams(params).toString() : '';
  return request({
    url: url + queryString,
    method: 'GET',
    params: params,
    header,
  });
}

export function post(url, data, header) {
  return request({
    url,
    method: 'POST',
    data,
    header,
  });
}
